import axios from 'axios';
/**
 * 操作
 */
const operations = {
  activate: { operate: '激活', method: 'activate' },
  deactivate: { operate: '停用', method: 'deactivate' },
  delete: { operate: '删除', method: 'delete' }
};
function replaceSolidus(name) {
  return name.replace('/', '');
}

/**
 * 时间格式化
 * @param date
 * @param fmt
 * @returns {string}
 */
function formatDate(date, fmt) {
  date = new Date(date);
  if (typeof fmt === 'undefined') {
    fmt = 'yyyy-MM-dd hh:mm:ss';
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length)
      );
    }
  }
  return fmt;
}

/**
 * 获取图片
 * @param {图片名称} name
 */
function showRemotePic(name) {
  console.log('--->111:' + name);
  if (isNetworkImage(name)) {
    return name;
  }
  return `${process.env.HOST_URL}image/detail/${name}`;
}

function commDownExcel(method, param, token) {
  let url = process.env.HOST_URL + method;
  new Promise(function(resolve, reject) {
    axios
      .post(url, param, {
        responseType: 'blob',
        headers: { Authorization: `Bearer ${token}` }
      })
      .then(function(response) {
        let data = response.data;
        if (!data) {
          return;
        }
        let contentDisposition = response.headers['content-disposition'];

        let fileName = contentDisposition.substring(
          contentDisposition.indexOf('=') + 2,
          contentDisposition.lastIndexOf('"')
        );
        fileName = decodeURI(fileName);
        let url = window.URL.createObjectURL(new Blob([data]));
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        //点击下载
        a.click();
        // 下载完成移除元素
        document.body.removeChild(a);
        // 释放掉blob对象
        window.URL.revokeObjectURL(url);
      })
      .catch(function(err) {
        rt.showErrorToast(err);
      });
  });
}
/**
 * 判断URL地址格式是否正确
 * @param {url地址}} url
 */
function checkURL(url) {
  let pattern = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
  if (url) {
    return pattern.test(url);
  }
  return false;
}

/**
 * 判断图片地址是否是网络图片
 * @param {图片地址} url
 */
function isNetworkImage(url) {
  let pattern = /(http|https):\/\/([\w.]+\/?)\S*/;
  return pattern.test(url);
}

export default {
  operations,
  replaceSolidus,
  formatDate,
  commDownExcel,
  showRemotePic,
  checkURL
};
